import React from 'react';
import {Typography, Input, Button, Popconfirm, Space, Spin, Form} from 'antd';
import TheButton from "@/components/TheButton";
import TheLoading from "@/components/TheLoading";
import TheTable from "@/components/TheTable";
import TheSpace from "@/components/TheSpace";
import {apiMenuIdentList, apiMenuIdentAdd, apiMenuIdentRemove} from "@/request/system/menu"

const Item = Form.Item;
const { Paragraph } = Typography;
class MenuPower extends React.Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: "权限名称",
                align: 'center',
                dataIndex: "identName"
            },
            {
                title: '权限标识',
                align: 'center',
                dataIndex: "identType",
                render: (text, record) => {
                    return <Paragraph style={{marginBottom:0}} copyable>{text}</Paragraph>
                }
            },
            {
                title: '操作',
                align: 'center',
                render: (text, record) => (
                    <TheButton type="link" size='small'
                               onClick={() => this.handleDelete(record.storeIdentId)}>删除</TheButton>
                ),
            },
        ];
        this.state = {
            count: 1,
            dataSource: [],
            dataLoading: false,
            menuId: props.storeMenuId
        };
    }

    // 初始化页面数据
    componentDidMount() {
        this.identDataLoading();
    }

    /**
     * 获取数据列表
     * @returns {Promise<void>}
     */
    async identDataLoading() {
        this.setState({
            dataLoading: true
        })
        const res = await apiMenuIdentList({menuId: this.state.menuId})
        if (res.code === 0) {
            this.setState({
                dataSource: res.data,
                count: res.data.length
            });
        }
        this.setState({
            dataLoading: false
        })
    }


    /**
     * @desc 权限删除
     * @params number {index} 需要删除的索引（物理删除 不走接口）
     * */
    handleDelete = (storeIdentId) => {
        const that = this;
        React.$confirm({
            title: "警告",
            content: "确定要删除吗？",
            onOk: async () => {
                const res = await apiMenuIdentRemove({storeIdentId: storeIdentId})
                if (res.code === 0) {
                    await this.identDataLoading()
                    React.$message({
                        type: "success",
                        content: "删除成功"
                    });
                }
            }
        });
        this.identDataLoading();
    };

    /**
     * @desc 添加权限
     * @params number {index} 需要删除的索引（物理删除 不走接口）
     * */
    identHandleAdd = (values) => {
        values.storeMenuId = this.state.menuId;
        this.identDataSave(values);
    };

    /**
     * todo 每次只能增加一条数据
     * @param data
     * @returns {Promise<void>}
     */
    async identDataSave(data) {
        const that = this;
        const res = await apiMenuIdentAdd(data);
        if (res.code === 0) {
            that.identDataLoading();
            that.formRef.resetFields()
        }
    }

    /**
     * @desc 添加菜单权限
     * */
    addMenuPower = () => {
        this.identDataSave(this.state.dataSource);
        console.log(this.state.dataSource)
    }

    handleSave = (row) => {
        const newData = [...this.state.dataSource];
        const index = newData.findIndex((item) => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {...item, ...row});
        this.setState({
            dataSource: newData,
        });
    };

    render() {
        const {dataSource} = this.state;
        const {handleCancel} = this.props;
        const columns = this.columns.map((col) => {
            if (!col.editable) {
                return col;
            }

            return {
                ...col,
                onCell: (record) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });

        return (
            <TheLoading loading={this.state.dataLoading}>
                <Form layout="inline" onFinish={this.identHandleAdd} style={{marginBottom: '10px'}} ref={ref => this.formRef = ref}>
                    <Item name="identName" label="权限名称">
                        <React.FormInput placeholder={'请输入权限名称'}/>
                    </Item>
                    <Item name="identType" label="权限标识">
                        <React.FormInput placeholder={'请输入权限标识'}/>
                    </Item>
                    <Item>
                        <TheButton type="primary" htmlType="submit" size="layer">
                            新增
                        </TheButton>
                    </Item>
                </Form>

                {/*表格*/}
                <TheTable
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={dataSource}
                    columns={columns}
                    pagination={false}
                    loading={this.state.dataLoading}
                />
                <div className="p-text-align" style={{marginTop: '10px'}}>
                    <TheSpace size="large">
                        <Button key="back" onClick={handleCancel}>
                            关 闭
                        </Button>
                    </TheSpace>
                </div>
            </TheLoading>
        );
    }
}

export default MenuPower
